package org.dxy.trigger.http;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.api.dto.request.workstation.CreateWorkstationRequestDto;
import org.dxy.api.dto.request.workstation.UpdateWorkstationRequestDto;
import org.dxy.api.dto.request.workstation.WorkstationInRequest;
import org.dxy.api.dto.request.workstation.WorkstationOutRequest;
import org.dxy.api.dto.response.R;
import org.dxy.api.dto.vo.WorkstationOperationVo;
import org.dxy.api.dto.vo.WorkstationReportVo;
import org.dxy.api.dto.vo.WorkstationRuntimeStatusVo;
import org.dxy.domain.handler.workstation.WorkstationInCommandHandler;
import org.dxy.domain.handler.workstation.WorkstationOutCommandHandler;

import org.dxy.infrastructure.persistent.po.query.WorkstationBasicViewPo;
import org.dxy.infrastructure.persistent.service.ProductionLineBasicViewService;
import org.dxy.infrastructure.persistent.service.WorkstationRuntimeViewService;
import org.dxy.infrastructure.persistent.service.WorkstationBasicViewService;
import org.dxy.trigger.http.service.WorkstationApplicationService;
import org.dxy.types.common.CommandResult;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 工位管理控制器
 * @author dxy
 * @createTime 2025/9/4
 */
@Slf4j
@RestController
@RequestMapping("/api/workstation")
@RequiredArgsConstructor
public class WorkstationController {

    private final WorkstationApplicationService workstationApplicationService;

    /**
     * @description 创建工位
     * @param dto 包含工位创建信息的请求DTO
     * @return 返回创建成功或失败的响应
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @PostMapping("/create")
    public R<Void> createWorkstation(@Validated @RequestBody CreateWorkstationRequestDto dto) {
        return workstationApplicationService.createWorkstation(dto);
    }

    /**
     * @description 分页查询工位列表（支持条件过滤）
     * @param page 分页参数（页码、每页大小等）
     * @param query 过滤条件（工位名称、状态、产线等）
     * @return 分页的工位列表响应
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @GetMapping("/page")
    public R<Page<WorkstationBasicViewPo>> page(
            @ParameterObject Page<WorkstationBasicViewPo> page,
            @ParameterObject WorkstationBasicViewPo query) {
        return workstationApplicationService.page(page, query);
    }

    /**
     * @description 更新工位信息
     * @param id 工位ID
     * @param dto 包含更新信息的请求DTO
     * @return 返回更新成功或失败的响应
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @PutMapping("/{id}")
    public R<Void> update(@PathVariable Long id, @Validated @RequestBody UpdateWorkstationRequestDto dto) {
        return workstationApplicationService.update(id, dto);
    }

    /**
     * @description 删除单个工位
     * @param id 工位ID
     * @return 返回删除成功或失败的响应
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable Long id) {
        return workstationApplicationService.delete(id);
    }

    /**
     * @description 批量删除工位
     * @param ids 工位ID列表
     * @return 返回批量删除成功或失败的响应
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @DeleteMapping("/batch")
    public R<Void> batchDelete(@RequestBody List<Long> ids) {
        return workstationApplicationService.batchDelete(ids);
    }

    /**
     * @description 获取工位详情
     * @param id 工位ID
     * @return 返回工位详情信息
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @GetMapping("/{id}")
    public R<WorkstationBasicViewPo> getById(@PathVariable Long id) {
        return workstationApplicationService.getById(id);
    }

    /**
     * @description 根据产线ID获取工位列表
     * @param productionLineId 产线ID
     * @return 返回工位列表
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @GetMapping("/productionLine/{productionLineId}")
    public R<List<WorkstationBasicViewPo>> getByProductionLineId(@PathVariable Long productionLineId) {
        return workstationApplicationService.getByProductionLineId(productionLineId);
    }

    /**
     * @description 根据产线ID获取启用状态的工位列表
     * @param productionLineId 产线ID
     * @return 返回启用状态的工位列表
     * @date 2025/9/4 20:01
     * @auther dxy
     */
    @GetMapping("/productionLine/{productionLineId}/enabled")
    public R<List<WorkstationBasicViewPo>> getEnabledByProductionLineId(@PathVariable Long productionLineId) {
        return workstationApplicationService.getEnabledByProductionLineId(productionLineId);
    }

    /**
     * @description 获取所有启用状态的工位列表
     * @return 返回所有启用状态的工位列表
     * @date 2025/10/19
     * @auther dxy
     */
    @GetMapping("/enabled")
    public R<List<WorkstationBasicViewPo>> getAllEnabledWorkstations() {
        return workstationApplicationService.getAllEnabledWorkstations();
    }

    /**
     * @description 获取可进站的工位列表（空闲状态）
     * @return 返回可进站的工位列表
     * @date 2025/10/19
     * @auther dxy
     */
    @GetMapping("/availableForIn")
    public R<List<WorkstationBasicViewPo>> getAvailableWorkstationsForIn() {
        return workstationApplicationService.getAvailableWorkstationsForIn();
    }

    /**
     * @description 获取可出站的工位列表（运行中状态）
     * @return 返回可出站的工位列表
     * @date 2025/10/19
     * @auther dxy
     */
    @GetMapping("/availableForOut")
    public R<List<WorkstationBasicViewPo>> getAvailableWorkstationsForOut() {
        return workstationApplicationService.getAvailableWorkstationsForOut();
    }

    // ==================== 工位操作相关接口 ====================

    /**
     * @description 工位进站
     * @param request 进站请求参数
     * @return 返回操作结果
     * @date 2025/10/13
     * @auther dxy
     */
    @PostMapping("/stationIn")
    public R<String> stationIn(@Validated @RequestBody WorkstationInRequest request) {
        log.info("工位进站操作: {}", request);
        return workstationApplicationService.stationIn(request);
    }

    /**
     * @description 工位出站
     * @param request 出站请求参数
     * @return 返回操作结果
     * @date 2025/10/13
     * @auther dxy
     */
    @PostMapping("/stationOut")
    public R<String> stationOut(@Validated @RequestBody WorkstationOutRequest request) {
        log.info("工位出站操作: {}", request);

        return workstationApplicationService.stationOut(request);
    }

    /**
     * @description 获取工位操作记录
     * @param workstationId 工位ID（可选）
     * @param workOrderCode 工单号（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 返回操作记录列表
     * @date 2025/10/13
     * @auther dxy
     */
    @GetMapping("/operation-records")
    public R<List<WorkstationOperationVo>> getOperationRecords(
            @RequestParam(required = false) Long workstationId,
            @RequestParam(required = false) String workOrderCode,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        List<WorkstationOperationVo> records = workstationApplicationService.queryOperationRecords(
                workstationId, workOrderCode, startTime, endTime);
        
        return R.ok(records, "查询成功");
    }

    /**
     * @description 获取工位报表数据
     * @param workstationId 工位ID（可选）
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 返回报表数据
     * @date 2025/10/13
     * @auther dxy
     */
    @GetMapping("/report")
    public R<List<WorkstationReportVo>> getWorkstationReport(
            @RequestParam(required = false) Long workstationId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        List<WorkstationReportVo> reports = workstationApplicationService.queryWorkstationReport(
                workstationId, startDate, endDate);
        
        return R.ok(reports, "查询成功");
    }

    /**
     * @description 获取实时工位状态
     * @return 返回实时状态列表
     * @date 2025/10/13
     * @auther dxy
     */
    @GetMapping("/real-time-status")
    public R<List<WorkstationRuntimeStatusVo>> getRealTimeStatus() {
        List<WorkstationRuntimeStatusVo> statusList = workstationApplicationService.queryRealTimeStatus();
        return R.ok(statusList, "查询成功");
    }


}